/**
 * 空间成员列表 ===》查看编辑页面
 */
import React from 'react';
import { connect, connectMaster, history } from 'umi';
import styles from './index.less';
import {
  Button,
  Form,
  Input,
  Space,
  Table,
  Tag,
  Select,
  message,
  Modal,
} from 'antd';
import { PlusOutlined, CloseOutlined } from '@ant-design/icons';
import moment from 'moment';
import { getMasterCommonPkg } from '@/utils/masterData';
const {
  utils: {
    otherUtil: { authorityVerify },
  },
} = getMasterCommonPkg();

@connectMaster //接收主服务数据
@connect(({ memberList, select }) => ({
  memberList,
  userLIstMap: select.userLIstMap,
}))
export default class extends React.Component {
  form = {};
  state = {
    detailId: '',
    selectContent: [], //添加成员选中的需要添加的成员
    roleObj: {}, //所有角色对应的个数
    roleList: [], //对应角色数组
    roleButInd: 0,
    oldMemberListTabDel: [],
  };
  componentDidMount = async () => {
    this.getAllRoleList();
    this.init();
    const {
      location: {
        query: { detailId },
      },
    } = history;
    this.setState({
      detailId: detailId,
    });
    this.getMemberListDetail(detailId);
  };

  //获取所有角色
  getAllRoleList = async () => {
    var rs = await this.props.dispatch({
      type: 'UserList/getAllRoleList',
    });
    console.log(rs.data, 'rs.data');
    // 成功
    if (rs.success) {
      let obj = {};
      rs.data.forEach(val => {
        obj[val.roleName] = 0;
      });
      this.setState({
        roleObj: obj,
        roleList: Object.keys(obj),
      });
    }
  };

  // 获取详情
  getMemberListDetail = async id => {
    let rs = await this.props.dispatch({
      type: 'memberList/getMemberListDetail',
      payload: { id: id },
    });
    if (rs.success) {
      this.changeState({
        detailList: rs.data,
        memberListTabDel: rs.data.workspaceUserList,
      });
      this.setState({
        oldMemberListTabDel: rs.data.workspaceUserList,
      });
      this.filterRole();
    }
  };

  // 筛选各个角色&&角色对应数量
  filterRole = () => {
    // const { memberListTabDel } = this.props.memberList;
    const { roleObj, oldMemberListTabDel } = this.state;
    if (oldMemberListTabDel.length !== 0) {
      oldMemberListTabDel.forEach(val => {
        val.roleList.forEach(item => {
          if (roleObj[item.roleName] >= 0) {
            let num = roleObj[item.roleName] + 1;
            roleObj[item.roleName] = num;
          }
        });
      });
      this.setState({
        roleObj,
      });
    }
  };

  // 根据角色筛选table数据
  filterRoleMenber = role => {
    const {oldMemberListTabDel} =this.state
    if (role === '全部') {
      this.changeState({
        memberListTabDel: oldMemberListTabDel,
      });
    } else {
      let arr = [];
      oldMemberListTabDel.forEach(val => {
        val.roleList.forEach(item => {
          // console.log(item.roleName === role)
          if (item.roleName === role) {
            arr.push(val);
          }
        });
      });
      console.log(arr, '点击对应筛选');
      this.changeState({
        memberListTabDel: arr,
      });
    }
  };

  // 筛选负责人
  init = async () => {
    // 获取用户列表
    await this.props.dispatch({
      type: 'select/getUserList',
      payload: { pageSize: 10000000, pageNum: 1 },
    });
  };

  // 添加成员
  // addWorkspaceUser = async () => {
  //   const { selectContent } = this.state;
  //   const { detailList } = this.props.memberList;
  //   if (selectContent.length == 0) return;
  //   let obj = {
  //     workspaceId: detailList.id,
  //     userIds: selectContent,
  //   };

  //   let rs = await this.props.dispatch({
  //     type: 'memberList/addWorkspaceUser',
  //     payload: obj,
  //   });
  //   if (rs.success) {
  //     this.setState({ selectContent: [] });
  //     message.success('添加成功');
  //     this.getMemberListDetail(this.state.detailId);
  //   }
  //   if (!rs.success) {
  //     message.error('添加失败');
  //   }
  // };

  // 删除成员
  deleteWorkspaceUser = async id => {
    const { detailList } = this.props.memberList;
    let obj = {
      workspaceId: detailList.id,
      userIds: [id],
    };
    Modal.confirm({
      title: '你确定要删除吗?',
      content: '你确定要删除吗?',
      centered: true,
      onOk: async () => {
        // 走接口删除
        let rs = await this.props.dispatch({
          type: 'memberList/deleteWorkspaceUser',
          payload: obj,
        });
        if (rs.success) {
          message.success('删除成功');
          this.getMemberListDetail(this.state.detailId);
        }
        if (!rs.success) {
          message.error('删除失败');
        }
      },
    });
  };
  //更新状态
  changeState = obj => {
    this.props.dispatch({
      type: 'memberList/setState',
      payload: obj,
    });
  };

  // 返回table列表
  renderTableData = (item, i) => {
    var roleList = item.roleList;
    const { type } = this.props.location.query;
    const { detailList } = this.props.memberList;
    return {
      key: i,
      1: item.userName,
      2: item.name,
      3: roleList?.map((item, ind) => (
        <Tag
          key={ind}
          style={{
            marginTop: '4px',
            border: '1px solid #00A0AB',
            color: '#00A0AB',
          }}
        >
          {item.roleName}
        </Tag>
      )),
      4: item.phone,
      5: item.email,
      options: type !== 'view' && (
        <div>
          <Space size="middle">
            <Button
              type="link"
              key={'delete'}
              onClick={() => {
                this.setState({
                  isModalVisible: true,
                  userId: item.userId,
                });
                // 调用删除接口
                this.deleteWorkspaceUser(item.userId);
              }}
              disabled={detailList.createId === item.userId ? true : false}
            >
              移除
            </Button>
          </Space>
        </div>
      ),
    };
  };

  // columns
  columns = () => {
    const { type } = this.props.location.query;
    let columns = [];
    if (type === 'view') {
      columns = [
        { title: '用户名', dataIndex: '1' },
        { title: '姓名', dataIndex: '2' },
        { title: '角色', dataIndex: '3' },
        { title: '电话', dataIndex: '4' },
        { title: '邮箱', dataIndex: '5' },
      ];
    } else {
      columns = [
        { title: '用户名', dataIndex: '1' },
        { title: '姓名', dataIndex: '2' },
        { title: '角色', dataIndex: '3' },
        { title: '电话', dataIndex: '4' },
        { title: '邮箱', dataIndex: '5' },
        { title: '操作', dataIndex: 'options', fixed: 'right' },
      ];
    }
    return columns;
  };
  // 标题
  headerTitle = data => {
    const { type } = this.props.location.query;
    if (type === 'add') return `工作空间：${data.name} (添加成员)`;
    if (type === 'view') return `工作空间：${data.name} (查看)`;
    if (type === 'edit') return `工作空间：${data.name} (编辑)`;
  };

  render() {
    const { type } = this.props.location.query;
    const {
      total,
      pageSize,
      pageNum,
      allMember,
      detailList,
      memberListTabDel,
      allRoleList,
    } = this.props.memberList;
    const { userLIstMap } = this.props;
    const { isModalVisible, roleList, roleObj, roleButInd } = this.state;
    return (
      <div className={styles.TableContain}>
        <div className={styles.FormTable}>
          <div className={styles.FormHeader}>
            <span>{this.headerTitle(detailList)}</span>
            <CloseOutlined
              onClick={() => {
                history.push(
                  {
                    ...this.props.location,
                    pathname: '/userManagement/memberList',
                  }
                )
              }}
            />
          </div>
          <div className={styles.AddMember}>
            <div>
              <Space className={styles.Space}>
                <span>负责人 ：</span>
                <span style={{ color: 'rgba(0, 0, 0, 0.65)' }}>
                  {userLIstMap[detailList.createId]?.name}
                </span>
              </Space>
            </div>
            {/* {type === 'add' && (
                <Space className={styles.Space}>
                  <span>添加成员 ：</span>
                  <Select
                    placeholder="请选择..."
                    mode="multiple"
                    allowClear
                    value={this.state.selectContent}
                    style={{ width: '440px' }}
                    showSearch
                    onChange={val => {
                      this.setState({
                        selectContent: val,
                      });
                    }}
                    filterOption={(inputValue, option) => {
                      return option.searchText.indexOf(inputValue) > -1;
                    }}
                  >
                    {allMember.map((item, ind) => {
                      //下拉框内容
                      return (
                        <Select.Option
                          key={item.id}
                          value={item.id}
                          searchText={item.name}
                          className={styles.opt}
                        >
                          <Space>
                            <span>{item.name}</span>
                            <span>
                              {item.roleVoList?.map(val => {
                                return (
                                  <Space>
                                    <Tag>{val.roleName}</Tag>
                                  </Space>
                                );
                              })}
                            </span>
                          </Space>
                        </Select.Option>
                      );
                    })}
                  </Select>
                  <Button
                    type="primary"
                    onClick={() => {
                      // 调用添加接口
                      this.addWorkspaceUser();
                    }}
                    // 点击添加成员
                  >
                    添加
                  </Button>
                </Space>
              )} */}
            {type === 'view' && (
              <Space className={styles.Space}>
                <span>创建时间 ：</span>
                <span style={{ color: 'rgba(0, 0, 0, 0.65)' }}>
                  {moment(detailList.createTime).format('YYYY-MM-DD HH:mm:ss')}
                </span>
              </Space>
            )}
          </div>
        </div>
        {/* table表格 */}
        <div className={styles.TableList}>
          <div className={styles.TableName}>
            <p
              style={{
                fontSize: '16px',
                color: 'rgba(0, 0, 0, 0.85)',
                fontWeight: 500,
              }}
            >
              成员列表
            </p>
            {/* {type === 'edit' && (
              <Button
                type="primary"
                onClick={() => {
                  if (!authorityVerify('UPDATE_SPACE_MEMBER')) return;
                  this.changeState({
                    operationType: 'add',
                  });
                  history.push({
                    pathname: '/userManagement/memberList/member',
                    query: {
                      type: 'add',
                      detailId: this.state.detailId,
                    },
                  });
                }}
              >
                添加成员
              </Button>
            ) } */}
          </div>
          {/* 筛选 */}
          <ul className={styles.roleNumber}>
            <Space>
              <li>
                <Button
                  type={roleButInd === 0 && 'primary'}
                  onClick={() => {
                    this.filterRoleMenber("全部");
                    this.setState({
                      roleButInd: 0,
                    });
                  }}
                >
                  全部
                </Button>
              </li>
              {roleList.map((item, ind) => {
                return (
                  <li
                    onClick={() => {
                      this.filterRoleMenber(item);
                      this.setState({
                        roleButInd: ind + 1,
                      });
                    }}
                  >
                    <Button
                      type={roleButInd === ind + 1 && 'primary'}
                    >{`${item}(${roleObj[item]})`}</Button>
                  </li>
                );
              })}
            </Space>
          </ul>

          <div className={styles.total} style={{ left: '10px' }}>
            共{total}条记录 第 {pageNum} /
            {(() => {
              var num = parseInt(total / pageSize);
              if (total % pageSize != 0) num += 1;
              return num;
            })()}{' '}
            页
          </div>
          <Table
            columns={this.columns()}
            pagination={false}
            scroll={{ y: '350px' }}
            dataSource={memberListTabDel?.map((item, i) =>
              this.renderTableData(item, i),
            )}
          />
        </div>
      </div>
    );
  }
}
